﻿using System;
using System.Collections.Generic;
using System.Text;
using DecodeInterface;
using System.Drawing.Imaging;
using System.Windows.Forms;

namespace DecodeLibrary
{
    public class DecodeYV12ToRGB : DecodeIntPtr
    {
        protected override unsafe object[] OnDecode(byte* pIn, byte* pOut, System.Drawing.Size sizeIn, System.Drawing.Size sizeOut, params object[] state)
        {
            int W = sizeOut.Width, H = sizeOut.Height;
            long size = W * H;
            int indexY = 0, indexUV = 0;

            byte* yData = pIn;
            byte* vData = &yData[size];
            byte* uData = &vData[size >> 2];

            byte y = 0, u = 0, v = 0;
            double temp = 0;

            for (int h = 0; h < H; h++)
            {
                for (int w = 0; w < W; w++)
                {
                    indexY = h * W + w;
                    indexUV = h / 2 * W / 2 + w / 2;

                    y = yData[indexY];
                    v = vData[indexUV];
                    u = uData[indexUV];

                    indexY *= 3;

                    temp = 1.164383 * (y - 16) + 2.017230 * (u - 128) + 0;
                    pOut[indexY++] = (byte)(temp < 0 ? 0 : (temp > 255 ? 255 : temp));

                    temp = (1.164383 * (y - 16) - 0.391762 * (u - 128) - 0.812969 * (v - 128));
                    pOut[indexY++] = (byte)(temp < 0 ? 0 : (temp > 255 ? 255 : temp));

                    temp = 1.164383 * (y - 16) + 0 + 1.596016 * (v - 128);
                    pOut[indexY] = (byte)(temp < 0 ? 0 : (temp > 255 ? 255 : temp));
                }
            }

            return null;
        }
    }
}
